package com.mms.service;

import java.sql.Connection;
import java.util.Date;
import java.util.List;

import com.mms.dao.CustomerMapper;
import com.mms.dao.CustomerMapperImpl;
import com.mms.dao.FollowUpMapper;
import com.mms.dao.FollowUpMapperImpl;
import com.mms.entity.Customer;
import com.mms.entity.CustomerState;
import com.mms.entity.FollowUp;
import com.mms.util.JdbcUtils;

public class FollowUpServiceImpl implements FollowUpService {

	private FollowUpMapper followUpMapper = new FollowUpMapperImpl();
	private CustomerMapper customerMapper = new CustomerMapperImpl();

	@Override
	public void save(FollowUp newFollowUp) {
		Connection conn = null;
		try {
			// ：：开启事务
			conn = JdbcUtils.getConnection();
			conn.setAutoCommit(false);
			// 操作1：插入跟进记录到followup表
			this.followUpMapper.insert(newFollowUp, conn);
			// 操作2：更新customer表中对应记录的last_follow_up_date、last_follow_up_note，如果经过本次跟进该客户成交了，还需更新state、deal_date
			int custId = newFollowUp.getCustId();
			Date lastFollowUpDate = newFollowUp.getFollowUpDate();
			String lastFollowUpNote = newFollowUp.getFollowUpNote();
			CustomerState state = newFollowUp.getCustomerState();
			// 先查到对应客户的原始数据
			Customer customer = this.customerMapper.selectByPrimaryKey(custId);
			// 无论如何，现在有一次新的跟进，必须涉及到更新对应客户的state、last_follow_up_date、last_follow_up_note
			customer.setState(state);
			customer.setLastFollowUpDate(lastFollowUpDate);
			customer.setLastFollowUpNote(lastFollowUpNote);
			// 如果经过本次跟进，该客户成交了，还得更新这个客户的成交日期deal_date
			if (newFollowUp.getCustomerState() == CustomerState.DEALED) {
				customer.setDealDate(newFollowUp.getFollowUpDate());
			}
			// 更新到数据库
			this.customerMapper.updateByPrimaryKey(customer, conn);
			// ：：提交事务
			conn.commit();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			JdbcUtils.close(conn);
		}

	}

	@Override
	public List<FollowUp> listFollowUpHistory(int custId) {
		// TODO Auto-generated method stub
		return null;
	}

}
